﻿using SuperiorShopBussinessService;
using System;
using System.Linq;
using System.Web.Mvc;
using SuperiorModel;
using SuperiorCommon;
using Redis;
using System.IO;

namespace SuperiorShopkeeper.Controllers
{
    [JsonException]
    [CheckLoginFitler]
    public class ShopAppController : BaseController
    {
        private readonly IShopAppService _IShopAppService;
        private readonly IShopAdminService _IShopAdminService;

        public ShopAppController(IShopAppService IShopAppService, IShopAdminService IShopAdminService)
        {
            _IShopAppService = IShopAppService;
            _IShopAdminService = IShopAdminService;
        }
        protected override void Dispose(bool disposin)
        {
            this._IShopAppService.Dispose();
            this._IShopAdminService.Dispose();
            base.Dispose(disposin);
        }
        // GET: ShopApp
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 商城列表
        /// </summary>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityMenuEnum.ShopAppList)]
        public ActionResult List()
        {
            var criteria = new ShopAppCriteria() { PagingResult = new PagingResult(0, 15), ShopAdminId = UserContext.DeSecretId, AppType = 999 };
            var model = GetShopAppTPagedModel(criteria);
            return View(model);
        }
        /// <summary>
        /// 搜索，分页请求的商城列表
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public ActionResult List(ShopAppCriteria criteria)
        {
            criteria.ShopAdminId = UserContext.DeSecretId;
            var model = GetShopAppTPagedModel(criteria);
            return PartialView("_List", model);
        }
        /// <summary>
        /// 检测当前小程序版本信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CheckVersion(string id, string authorizer_appid = "", string act = "")
        {
            string _id = base.ValidataParms(id);
            var model = _IShopAppService.GetShopAppModel(_id.ToInt());
            if (authorizer_appid != "" && act != "")
            {
                //授权回调回来
                if (model.AppId != authorizer_appid)
                {
                    ViewBag.Msg = "请当前小程序管理员,将当前小程序权限授权给优越店长!";
                    return View(model);
                }


                //上传代码
                var data = new ThirdCommitParams();
                data.template_id = ConfigSettings.Instance.TemplateId.ToInt();
                var lastVersion = RedisManager.GetLasterItemFromList<VersionItem>("Version");
                //存储这个版本号，发布成功后，取出更新，原因：在审核发布的过程中，如果还有最新的版本，直接从redis取最新的，可能会造成版本不一致的问题
                RedisManager.Set<string>("CurrentSubimiVersion_" + id, lastVersion.Version, DateTime.Now.AddYears(20));
                data.user_version = lastVersion.Version;
                data.user_desc = lastVersion.Msg;
                //配置ext.json
                var extModel = new ExtJosn();
                extModel.extAppid = authorizer_appid;
                extModel.ext.name = model.ShopName;
                extModel.ext.said = model.ShopAdminId;
                extModel.ext.spid = model.Id;
                data.ext_json = extModel.ToJson();
                LogManger.Instance.WriteLog("上传代码JSON：" + data.ToJson());
                var res = InterfaceApi.Commit(act, data);
                if (res.errcode == 0 && res.errmsg == "ok")
                {
                    ViewBag.Msg = "上传成功,请获取体验查看,请在2小时内完成获取体验和提交审核!";
                }
                else
                {
                    ViewBag.Msg = "上传失败";
                    LogManger.Instance.WriteLog("上传返回代码:" + res.ToJson());
                }

            }
            //将id存cookie中，授权回调获取
            if (authorizer_appid == "")
                CookieHelper.SetCookie("PROGRAME_ID", id, DateTime.Now.AddMinutes(5));
            return View(model);
        }
        /// <summary>
        /// 获取体验小程序二维码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult GetQrCode(string id)
        {
            //从redis读取上传代码时，回调存储的authorizer_access_token授权令牌
            var authorizer_access_token = RedisManager.Get<string>("authorizer_access_token_" + id);
            if (authorizer_access_token == null)
                return Error("授权令牌过期，请重新上传代码,才能获取");
            var response = InterfaceApi.GetQrCode(authorizer_access_token);
            LogManger.Instance.WriteLog("获取体验小程序的接口返回数据:" + response);
            //将图片保存到临时图片目录
            var image = ImgTool.BytesToImage(response);
            var url = Path.Combine(ProductBannerUploader.Instance.TempPhysicalPath, "QrCode_" + id + ".jpg");
            image.Save(url);
            //返回保存后得图片路径
            var res = ConfigSettings.Instance.ImageHost + ProductBannerUploader.Instance.TempRelativePath + "/" + "QrCode_" + id + ".jpg";
            return Success(res);
        }

        /// <summary>
        /// 提交代码审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityOptionEnum.UploadVersion)]
        [AjaxOnly]
        public JsonResult SubmitCode(string id, string tag)
        {
            //从redis读取上传代码时，回调存储的authorizer_access_token授权令牌
            string _msg = "";
            var authorizer_access_token = GetAuthorizer_access_token(id, out _msg);
            if (!string.IsNullOrEmpty(_msg))
                return Error(_msg);
            //获取该小程序服务类目列表
            var categorysJosn = InterfaceApi.GetCategorys(authorizer_access_token);
            LogManger.Instance.WriteLog("获取该小程序服务类目列表:" + categorysJosn);
            var categoryModel = SuperiorCommon.Json.ToObject<Wx_CategoryResponseModel>(categorysJosn);
            if (categoryModel.errcode != 0)
                return Error(categoryModel.errmsg);
            //获取小程序的第三方提交代码的页面配置
            var pagesJson = InterfaceApi.GetPages(authorizer_access_token);
            LogManger.Instance.WriteLog("获取小程序的第三方提交代码的页面配置:" + pagesJson);
            var pagesModel = SuperiorCommon.Json.ToObject<Wx_PagesResponseModel>(pagesJson);
            if (pagesModel.errcode != 0)
                return Error(pagesModel.errmsg);
            //配置提交POST模型
            var reqModel = new Wx_SubimitModel();
            var item = new Wx_SubimitItem();//最少1项，最多5项，暂时只提交首页
            var _category = categoryModel.category_list.FirstOrDefault();//取第一个服务类目
            item.address = pagesModel.page_list.FirstOrDefault();

            item.tag = tag;
            item.first_class = _category.first_class;
            item.second_class = _category.second_class;
            item.third_class = _category.third_class;
            item.first_id = _category.first_id;
            item.second_id = _category.second_id;
            item.third_id = _category.third_id;
            item.title = "首页";
            reqModel.item_list.Add(item);
            LogManger.Instance.WriteLog("提交POST模型:" + reqModel.ToJson());
            var res = InterfaceApi.Submit(authorizer_access_token, reqModel);
            if (res.errcode != 0)
                return Error(res.errmsg);
            //记录当前小程序得审核信息到redis
            var info = new ShopAppCheckInfo(0, res.auditid);
            RedisManager.Set<ShopAppCheckInfo>("CheckInfo_" + id, info, DateTime.Now.AddYears(20));
            return Success(true);

        }
        /// <summary>
        /// 获取微信审核结果
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityOptionEnum.GetWxCheckResult)]
        [AjaxOnly]
        public JsonResult GetCheckResult(string id)
        {
            //获取当前小程序reids中得审核信息
            var info = RedisManager.Get<ShopAppCheckInfo>("CheckInfo_" + id);
            if (info == null)
                return Error("审核信息为空");
            string _msg = "";
            var authorizer_access_token = GetAuthorizer_access_token(id, out _msg);
            if (!string.IsNullOrEmpty(_msg))
                return Error(_msg);
            //读取审核结果
            var res = InterfaceApi.GetCheckResult(authorizer_access_token, new { auditid = info.Auditid });
            if (res.errcode != 0)
                return Error(res.errmsg);
            //更改redis checkinfo状态
            if (res.status != 2)//审核中
            {
                if (res.status == 0)//成功
                {
                    info.Status = 1;
                }
                else if (res.status == 1)//失败
                {
                    info.Status = 2;
                    info.ErrorMsg = res.reason;
                }
                info.UpdateTime = DateTime.Now;
            }
            RedisManager.Set<ShopAppCheckInfo>("CheckInfo_" + id, info, DateTime.Now.AddYears(20));
            return Success(res);
        }
        /// <summary>
        /// 重置上传=》发布流程，删除checkinfo信息，在发生未知错误时使用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityOptionEnum.ResetAllPublic)]
        [AjaxOnly]
        public JsonResult ResetProcess(string id)
        {
            RedisManager.Remove("CheckInfo_" + id);
            return Success(true);
        }
        /// <summary>
        /// 发布小程序
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityOptionEnum.PublicProgram)]
        [AjaxOnly]
        public JsonResult Release(string id)
        {
            string _msg = "";
            var authorizer_access_token = GetAuthorizer_access_token(id, out _msg);
            if (!string.IsNullOrEmpty(_msg))
                return Error(_msg);
            var res = InterfaceApi.Release(authorizer_access_token);
            if (res.errcode != 0)
                return Error(res.errmsg);
            //发布成功，清楚checkinfo信息，因为只保存最近一次，下一次提交审核会产生最新得
            RedisManager.Remove("CheckInfo_" + id);
            //更新当前小程序版本号
            string _id = base.ValidataParms(id);
            var currentVersion = Redis.RedisManager.Get<string>("CurrentSubimiVersion_" + id);
            _IShopAppService.UpdateVersion(_id.ToInt(), currentVersion);
            return Success(true);
        }
        /// <summary>
        /// 获取用户授权令牌
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GetAuthorizer_access_token(string id, out string msg)
        {
            msg = "";
            var authorizer_access_token = RedisManager.Get<string>("authorizer_access_token_" + id);
            if (authorizer_access_token == null)
            {
                string _id = base.ValidataParms(id);
                var model = _IShopAppService.GetShopAppModel(_id.ToInt());
                //获取当前小程序刷新令牌刷新authorizerToken
                var authorizer_refresh_token = RedisManager.Get<string>("authorizer_refresh_token_" + id);
                if (authorizer_refresh_token == null)
                {
                    msg = "刷新令牌丢失，请重新授权上传代码";
                    return "";
                }
                var component_token = RedisManager.Get<string>("Component_token");
                if (component_token == null)
                {
                    msg = "请稍后再试";
                    return "";
                }
                //刷新authorizer_access_token
                var refresh_res = InterfaceApi.Refresh_authorizer_token(component_token, model.AppId, authorizer_refresh_token);
                LogManger.Instance.WriteLog("刷新授权令牌JSON:" + refresh_res.ToJson());
                //重新缓存authorizer_access_token和authorizer_refresh_token
                //存储当前用户授权authorizer_access_token,2小时
                RedisManager.Set<string>("authorizer_access_token_" + id, refresh_res.authorizer_access_token, DateTime.Now.AddMinutes(120));
                //存储当前用户得刷新令牌
                RedisManager.Set<string>("authorizer_refresh_token_" + id, refresh_res.authorizer_refresh_token, DateTime.Now.AddYears(20));
                authorizer_access_token = refresh_res.authorizer_access_token;
            }
            return authorizer_access_token;
        }

        /// <summary>
        /// 获取商城列表分页模型
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public TPagedModelList<ShopAppModel> GetShopAppTPagedModel(ShopAppCriteria criteria)
        {
            var query = _IShopAppService.ShopAppList(criteria);
            return new TPagedModelList<ShopAppModel>(query, query.PagingResult);
        }

        /// <summary>
        /// 添加小程序页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            return View();
        }
        public ActionResult Add_H5()
        {
            return View();
        }

        /// <summary>
        /// 提交商城
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        [ShopAuthority(AuthorityOptionEnum.AddShopApp)]
        public JsonResult Add(ShopAppModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            string msg = "";
            model.ShopAdminId = UserContext.DeSecretId;
            var ret = _IShopAppService.Add(model, out msg);
            if (ret != 1)
                return Error(msg);
            return Success(true);
        }

        /// <summary>
        /// 修改页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(string id)
        {
            string _id = base.ValidataParms(id);
            if (_id == null)
                return Error("非法参数");
            var model = _IShopAppService.GetShopAppModel(_id.ToInt());
            return View(model);
        }
        /// <summary>
        /// 修改H5页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit_H5(string id)
        {
            string _id = base.ValidataParms(id);
            if (_id == null)
                return Error("非法参数");
            var model = _IShopAppService.GetShopAppModel(_id.ToInt());
            return View(model);
        }

        /// <summary>
        /// 提交修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// 
        [AjaxOnly]
        [HttpPost]
        [ShopAuthority(AuthorityOptionEnum.EditShopApp)]
        public JsonResult Edit(ShopAppModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.Id = base.ValidataParms(model.Id);
            if (model.Id == null)
                return Error("非法参数");
            string msg = "";
            model.ShopAdminId = UserContext.DeSecretId;
            var ret = _IShopAppService.Edit(model, out msg);
            if (ret != 1)
                return Error(msg);
            //控制redis
            RedisManager.Remove("GetShopAppModel_" + model.Id);
            return Success(true);
        }

        /// <summary>
        /// 充值记录
        /// </summary>
        /// <returns></returns>
        public ActionResult RechargeList()
        {
            var criteria = new RechareOrderCriteria() { ShopAdminId = UserContext.DeSecretId.ToInt(), PagingResult = new PagingResult(0, 20), OrderStatus = 999, AppType = 999, SallType = 999 };
            var model = GetRechargeOrderPagedListManager(criteria);
            return View(model);
        }
        /// <summary>
        /// 搜索充值记录
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public ActionResult RechargeList(RechareOrderCriteria criteria)
        {
            criteria.ShopAdminId = UserContext.DeSecretId.ToInt();
            var model = GetRechargeOrderPagedListManager(criteria);
            return PartialView("_RechargeList", model);
        }
        private TPagedModelList<RechargeOrderModel> GetRechargeOrderPagedListManager(RechareOrderCriteria criteria)
        {
            var query = _IShopAdminService.SearchRechareOrderPageList(criteria);
            return new TPagedModelList<RechargeOrderModel>(query, query.PagingResult);
        }
        /// <summary>
        /// 商城首页预览
        /// </summary>
        /// <returns></returns>
        public ActionResult Priview()
        {
            //读取当前商户的一个商城。
            var criteria = new ShopAppCriteria() { PagingResult = new PagingResult(0, 15), ShopAdminId = UserContext.DeSecretId, AppType = 999 };
            var model = GetShopAppTPagedModel(criteria);
            var shop = model.TList.FirstOrDefault();
            ViewBag.Shop = shop;
            return View();
        }
    }
}